#!/usr/bin/python
"""
View iCalendar file and import it into google calendar.
"""
import sys
import os

import vobject

import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

class CalendarEvent:
	summary = ""
	dtstart = ""
	dtend = ""
	description = ""
	location = ""
	attendee = []
	organizer = {}
	uid = ""

	def __init__(self, vevent):
		self.summary = vevent.summary.value

		self.dtstart = vevent.dtstart.value.strftime("%Y-%m-%dT%H:%M:%S%z")
		self.dtend = vevent.dtend.value.strftime("%Y-%m-%dT%H:%M:%S%z")

		if hasattr(vevent, "description") :
			self.description = vevent.description.value
		if hasattr(vevent, "location") :
			self.location = vevent.location.value
		if hasattr(vevent, "organizer") :
			self.organizer = self.__toUserDesc(vevent.organizer)

		# get all attendee
		for line in vevent.lines():
			if line.name == "ATTENDEE" :
				self.attendee.append(self.__toUserDesc(line))

		if hasattr(vevent, "uid") :
			self.uid = vevent.uid.value

	
	def __toUserDesc(self, line) :
		ret = {}
		ret["email"] = line.value.replace("MAILTO:", "", 1)
		if line.params.has_key("CN") :
			ret["displayName"] = "".join(line.params["CN"])
		return ret



class CalendarImport:
	events = []
	service = None
	cookieFile = os.path.expanduser("~/.lbprod/calendar.dat")

	def __init__(self, path):
		f = open(path, "rb")
		cal = vobject.readComponents(f).next()

		for ve in cal.components():
			if ve.name != "VEVENT" :
				continue
			ce = CalendarEvent(ve)
			self.events.append(ce)
	
	def view(self, e):
		print "SUMMARY: " + e.summary
		print "DTSTART: " + e.dtstart
		print "DTEND: " + e.dtend
		print "LOCATION: " + e.location
		print "ORGANIZER: " + " ".join([ "%s" % v for (k, v) in  e.organizer.items()])
		# print e.attendee
		print "ATTENDEE: " + ";".join([ " ".join([ "%s" %v for(k,v) in p.items()]) for p in e.attendee ])
		print "-------"
		print e.description
		# print e.uid

	def process(self) :
		for e in self.events :
			# print "===================================================="
			self.view(e)

			print "Add this calendar event to google calendar? (yes/[no]): ",
			cmd = sys.stdin.readline().strip()
			if not cmd.lower() == 'y' and not cmd.lower() == 'yes' :
				continue
			
			if self.service is None:
				self.googleAuth()

			self.googleCalImport(e)


	def googleCalImport(self, ce) :
		# add myself to attendee, to make googel happy
		ce.attendee.append( { 'email' : 'zjuliubin@gmail.com', 'displayName' : 'liubin', "self": True } );

		googleCalEvent = {
				'summary': ce.summary,
				'location': ce.location,
				'organizer' : ce.organizer,
				'start' : {
					'dateTime': ce.dtstart
					},
				'end': {
					'dateTime': ce.dtend
					},
				'attendees': ce.attendee,
				'description' : ce.description,
				'iCalUID': ce.uid
				}
		gevent = self.service.events().import_(calendarId='primary', body=googleCalEvent).execute()
		if gevent is not None :
			print "Add to google calendar success!"
		else :
			print "Add to google calendar failed!"

		return gevent

	def googleAuth(self) :
		FLAGS = gflags.FLAGS

		# Set up a Flow object to be used if we need to authenticate. This
		# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
		# the information it needs to authenticate. Note that it is called
		# the Web Server Flow, but it can also handle the flow for native
		# applications
		# The client_id and client_secret are copied from the API Access tab on
		# the Google APIs Console
		FLOW = OAuth2WebServerFlow(
				client_id='865582306017.apps.googleusercontent.com',
				client_secret='nifSG9pAwIQEvHL0SZbZnWk8',
				scope='https://www.googleapis.com/auth/calendar',
				user_agent='lbprod/0.1')

		# To disable the local server feature, uncomment the following line:
		FLAGS.auth_local_webserver = False

		# If the Credentials don't exist or are invalid, run through the native client
		# flow. The Storage object will ensure that if successful the good
		# Credentials will get written back to a file.
		storage = Storage(self.cookieFile)
		credentials = storage.get()
		if credentials is None or credentials.invalid == True:
			credentials = run(FLOW, storage)

		# Create an httplib2.Http object to handle our HTTP requests and authorize it
		# with our good Credentials.
		http = httplib2.Http()
		http = credentials.authorize(http)

		# Build a service object for interacting with the API. Visit
		# the Google APIs Console
		# to get a developerKey for your own application.
		self.service = build(serviceName='calendar', version='v3', http=http,
				developerKey='YOUR_DEVELOPER_KEY')


if __name__ == "__main__" :
	if len(sys.argv) < 2 :
		print sys.argv[0] + " icalendar_file"
		exit(1)
	ci = CalendarImport(sys.argv[1])
	ci.process()

